/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.jaiky.imagespickers.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.media.common.Source;
import ohos.media.image.DataSourceUnavailableException;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.photokit.metadata.AVMetadataHelper;
import ohos.media.photokit.metadata.AVStorage;
import ohos.media.player.Player;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.Optional;

/**
 * description : 文件工具类
 *
 * @since 2021-04-15
 */
public class FileUtils {
    /**
     * 图片file转换PixelMap
     *
     * @param filePath filePath
     * @return PixelMap PixelMap
     */
    public static PixelMap getPixMap(String filePath) {
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        sourceOptions.formatHint = "image/jpeg";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
        FileInputStream fileInputStream = null;
        PixelMap pixelMap = null;
        try {
            File myFile = new File(filePath);
            fileInputStream = new FileInputStream(myFile);
            ImageSource imageSource = ImageSource.create(fileInputStream, sourceOptions);
            pixelMap = Optional.ofNullable(imageSource.createPixelmap(decodingOptions)).get();
            fileInputStream.close();
            return pixelMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pixelMap;
    }

    /**
     * Uri转换PixMap
     *
     * @param path    path
     * @param context context
     * @return PixelMap PixelMap
     */
    public static PixelMap getPixMapFromUri(String path, Context context) {
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        FileDescriptor filedesc = null;
        PixelMap pixelMap = null;
        try {
            filedesc = helper.openFile(Uri.parse(path), "r");
            ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            ImageSource imageSource = ImageSource.create(filedesc, null);
            pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);
            helper.release();
            return pixelMap;
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return pixelMap;
    }

    /**
     * 视频文件获取第一帧PixMap
     *
     * @param path 视频文件path
     * @return PixelMap
     */
    public static PixelMap getFirstPixelMap(String path) {
        AVMetadataHelper avMetadataHelper = new AVMetadataHelper();
        try {
            avMetadataHelper.setSource(path);
        } catch (DataSourceUnavailableException e) {
            e.printStackTrace();
        }
        PixelMap pixelMap = avMetadataHelper.fetchVideoPixelMapByTime(0);
        return pixelMap;
    }

    /**
     * 获取MP4文件的时长无效
     *
     * @param context context
     * @param file    file
     * @return 时长
     */
    public static int getDuration(Context context, File file) {
        try (FileInputStream in = new FileInputStream(file)) {
            FileDescriptor fd = in.getFD();
            Source source = new Source(fd);
            Player impl = new Player(context);
            impl.setSource(source);
            int duration = impl.getDuration();
            return duration;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 将图片保存到相册
     *
     * @param fileName 图片名称
     * @param pixelMap 图片的pixelMap
     * @param context  context
     * @return Uri
     */
    public static Uri saveImageToGallery(String fileName, PixelMap pixelMap, Context context) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");
            // 应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            // 这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
            packingOptions.format = "image/jpeg";
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    long dataSize = imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            // 解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return uri;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将视频保存到相册
     *
     * @param absolutePath 视频的绝对路径
     * @param fileName     视频的名称
     * @param context      context
     */
    public static void saveVideoToGallery(String absolutePath, String fileName, Context context) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Video.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/Camera/");
            valuesBucket.putString(AVStorage.Video.Media.MIME_TYPE, "video/MPEG_4");
            // 应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            int id = helper.insert(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            // 这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            OutputStream outputStream = new FileOutputStream(fd);
            File file = new File(absolutePath + fileName);
            FileInputStream fis = new FileInputStream(file);
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 开始读取
            while ((len = fis.read(bs)) != -1) {
                outputStream.write(bs, 0, len);
                outputStream.flush();
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            fis.close();
            // 解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
        } catch (DataAbilityRemoteException | IOException e) {
            e.printStackTrace();
        }
    }
}
